<template>
    <div class="shopContainer">
        <!-- 收获地址 -->
        <!-- <h1>checkIds: {{ checkIds }}</h1> -->
        {{ $store.getters.getCarSelectedGoodsId }}
        <div v-if="carData.length" class="addressWrap">
            <div  v-if="hasAddress"  class="address">
                <van-icon name="location-o" />
                <div class="info">
                    <div>{{ address.name }} / {{ address.tel }} 邮编: {{ address.postalCode }}</div>
                    <div>{{ address.province }}/{{ address.city }}/{{ address.country }}/{{ address.addressDetail }}</div>
                </div>
            </div>
            <!-- 无设置收货地址 -->
            <van-button v-else block type="info" @click="$router.push('/addaddress')" plain>添加地址</van-button>
        </div>

        <!-- 购物车列表 -->
        <div class="cartlist">
            <div class="item" v-for="(item,index) in carGoods" :key="item.id">
                <van-checkbox icon-size="24px" v-model="$store.getters.getGoodsSelected[item.id]"
                    @click="checkBoxChange(item.id, $store.getters.getGoodsSelected[item.id])" checked-color="#ee0a24" />
                <div class="imgWrap">
                    <img :src="item.thumb_path">
                </div>
                <div class="info">
                    <div class="title">{{ item.title }}</div>
                    <div class="area">
                        <div class="price">&yen;{{ item.sell_price }}</div>
                        <van-stepper theme="round" v-model="$store.getters.getGoodsNumber[item.id]"
                            @change="changeNumber(item.id, $store.getters.getGoodsNumber[item.id])" button-size="22"
                            disable-input />
                        <van-button type="danger" @click="delCarGoods(item.id,index)">删除</van-button>
                    </div>
                </div>
            </div>

        </div>

        <!-- 没有购物车商品时展示 -->
        <div class="emptyCar" v-if="carData.length === 0">
            <van-empty class="custom-image" :image="emptyCar" description="你的购物车空空如也">
                <van-button @click="$router.replace('/home/index')" type="danger" class="bottom-button">去首页</van-button>
            </van-empty>
        </div>

        <!-- 提交订单 -->
        <van-submit-bar @submit="onSubmit" :disabled="isDisabled" :price="$store.getters.getCarTotalPrice" button-text="提交订单">
            <template #tip>
                默认仅支持微信支付
            </template>
            <template #default>
                共选中 {{ $store.getters.getCarSelectedTotal }} 件
            </template>
        </van-submit-bar>
    </div>
</template>

<script>
import {genOrderId} from "../utils/tools.js"
import { fetchUserAddress,fetchCarGoods } from "../api/user.js"
import { fetchCommitOrder} from "../api/order.js"
import emptyCar from "../assets/images/car.png"
export default {
    data() {
        return {
            emptyCar,
            ids:this.$store.getters.getCarGoodsId,
            carData: this.$store.state.carData,
            carGoods:[],
            address:{}, // 收货地址
            hasAddress:false, // 记录是否有地址
        }
    },
    computed:{
        isDisabled(){
            // vuex中的数据变化了，计算属性computed也会重新计算
            if(this.hasAddress === false || this.carData.length === 0 || !this.$store.getters.getCarSelectedGoodsId){
                // 订单按钮不可用
                console.log('订单按钮不可用')
                return true
            }
             console.log('订单按钮可用')
            return false;
        }

    },
    async created() {
        // 获取用户地址
        if(!this.ids){
            return;
        }
        // 获取购物车商品
        this._fetchCarGoods()
        
        let user_id = this.$store.state.userInfo.id;
        let result = await fetchUserAddress(user_id);
        // 考虑地址多种情况 0个 1个 多个
        if(result.length === 0){
            this.hasAddress = false;
            this.$dialog({
                message: '请完善收货地址'
            })
            return;
        }else {
            this.hasAddress = true;
        }
        
        if(result.length === 1){
            this.address = result[0]
            return;
        }

        // 多个地址取出默认地址作为收货地址(可能无默认地址)
        let defaultAddress = result.find(item => item.isDefault == 1)

        if(defaultAddress){
            // 有默认地址
            this.address = defaultAddress
        }else {
            // 没有默认地址
            this.address = result[0]
        }
    },
    methods: {
        async _fetchCarGoods(){
           let {message} =  await fetchCarGoods(this.ids)
           this.carGoods = message
        },
        checkBoxChange(id, selected) {
            this.$store.commit('updCarGoodsSelected', { id, selected })
        },
        changeNumber(id, number) {
            this.$store.commit('updCarGoodsNumber', { id, number })
        },
        delCarGoods(id,index) {
            // 删除carGoods中的商品
            this.carGoods.splice(index,1)
            this.$store.commit('delCarGoods', id)
        },
        // 提交订单
        async onSubmit(){
            // 1. 准备订单参数
            let orderData = {
                user_id: this.$store.state.userInfo.id,
                order_id: genOrderId(),
                address_id: this.address.id,
                goods_ids: this.$store.getters.getCarSelectedGoodsId,
                number: this.$store.getters.getCarSelectedTotal,
                total_price: this.$store.getters.getCarTotalPrice,
            }
            // 2. 调用api,提交订单
            console.log(orderData)
            // 开启loading（持续提示）
            this.$toast.loading({
                duration: 0, // 持续展示 toast
                forbidClick: true,
                message: '提交订单中...',
            });
            let {message,status} = await fetchCommitOrder(orderData)
            // 关闭loading
            this.$toast.clear();
           
            if(status !== 0){
                // 订单异常
                this.$toast('网络繁忙，请稍后再试')
                return;
            }
            // 订单成功后：1. 清空购物车 2. 并跳转订单列表
            this.$store.commit('clearCar')
            this.$router.replace('/order')

        }
    },
}
</script>

<style lang="scss" scoped>
.shopContainer {

    .addressWrap {
    .address {
      display: flex;
      align-items: center;
      padding: 4px 10px;
      background-color: #fff;
      border-radius: 6px;
      margin: 6px 0;

      .van-icon {
        margin-right: 20px;
        color: red;
        font-size: 20px;
      }
    }
  }

    .cartlist {
        .item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 4px;
            background-color: #fff;
            border-radius: 6px;
            margin: 6px 0;

            .imgWrap {
                width: 50px;
                height: 50px;
                padding: 4px;

                img {
                    width: 100%;
                    height: 100%;
                }
            }

            .info {
                display: flex;
                flex-direction: column;
                justify-content: space-between;

                .title {
                    width: 70vw;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    display: -webkit-box;
                    -webkit-line-clamp: 1;
                    -webkit-box-orient: vertical;
                }

                .area {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;

                    .price {
                        color: #ff424a;
                    }
                }
            }
        }
    }

    .van-submit-bar {
        bottom: 50px;
    }
}
</style>